
/* $Log: Command.c,v $
/* Revision 1.23  2009/11/30 15:33:38  dimitrip
/* Added new command - SM ( Send SMS message )
/*
/* Revision 1.22  2009/11/11 09:20:42  dimitrip
/* Car Petrol Blocking update: if (registration > 2 min) reset;
/*
/* Revision 1.21  2009/11/03 10:54:21  dimitrip
/* Add "Car. Petrol Blocking" application
/*
/* Revision 1.20  2009/10/29 10:25:19  dimitrip
/* Add Print_SMS application
/*
/* Revision 1.19  2007/12/12 09:30:41  dimitrip
/* Add: Command Macro
/*
/* Revision 1.18  2007/12/10 09:08:47  dimitrip
/* *** empty log message ***
/*
/* Revision 1.17  2007/10/31 16:27:23  dimitrip
/* Add fews  command see CommandIterface.txt
/*
/* Revision 1.16  2007/10/29 16:59:23  dimitrip
/* *** empty log message ***
/*
/* Revision 1.15  2007/10/29 14:38:36  dimitrip
/* *** empty log message ***
/*
/* Revision 1.14  2007/10/05 18:31:56  Administrator
/* Implemented RF transmitter;
/* see RFT & RT command;
/*
/* Revision 1.13  2007/09/28 22:50:28  Administrator
/* RF Transmitter
/*
/* Revision 1.12  2007/09/25 17:11:40  dimitrip
/* *** empty log message ***
/*
/* Revision 1.11  2007/09/09 10:57:03  dimitrip
/* Add RF Remote, ARM mode;
/*
/* Revision 1.10  2007/08/26 16:54:05  dimitrip
/* *** empty log message ***
/*
/* Revision 1.9  2007/08/26 16:06:25  dimitrip
/* RF - OK;
/*
/* Revision 1.8  2007/04/06 13:14:04  dimitrip
/* 1. Check hardware of new board;
/* 2. Integration of MOTOROLA G24 modem;
/*
/* Revision 1.7  2007/02/05 12:30:39  dimitrip
/* *** empty log message ***
/*
/* Revision 1.8  2007/01/09 17:08:21  dimitrip
/* *** empty log message ***
/*
/* Revision 1.6  2006/12/28 16:10:07  dimitrip
/* *** empty log message ***
/*
/* Revision 1.5  2006/12/21 16:13:25  dimitrip
/* *** empty log message ***
/*
/* Revision 1.4  2006/12/17 17:00:07  dimitrip
/* *** empty log message ***
/*
/* Revision 1.3  2006/12/14 15:58:22  dimitrip
/* *** empty log message ***
/*
/* Revision 1.2  2006/12/07 16:24:44  dimitrip
/* *** empty log message ***
/* */

//#include "main.h" 
#include "ex_eeprom.h"
#include "printf.h"
#include "Print.h"
#include "Command.h"
#include "my_macros.h"
#include "Application.h"
#include "string.h"
#include "ModemService.h"
#include "USART.h"
//#include "DataMode.h"
#include "eeprom.h"
#include "FUpdate.h"
#include "Config.h"
#include "Passwords.h"
#include "Status.h"
#include "Analog.h"
#include "AuxPort.h"
#include "PhoneNumbers.h"
#include "ex_eeprom.h"
#include "Debug.h"
#include "InputsHandlers.h"
#include "Consts.h"
#include "RF_Manager.h"
#include "hardware.h"
#include "Outputs.h"
#include "CmdMacros.h"
#include "NeighborCells.h"
#include "SysTime.h"
#include "Tools.h"
#include "Receivers.h"
#include "Car_PetrolBlocking.h"


extern const char	STR__OK[];
extern unsigned char RF_Tx_Buffer[];
extern volatile near bit RF_TX_START;

/* #include <pic18.h> */
/* #include "printf.h" */
/* #include "Application.h" */
/* #include "my_macros.h" */
/* #include "Command.h" */
/* #include "Print.h" */
/* #include "string.h" */
/* #include "ModemService.h" */
/* #include "Sys_Strings.h" */
/* #include "USART.h" */
/* #include "Passwords.h" */
/* #include "DataMode.h" */
/* #include "eeprom.h" */
/* #include "FUpdate.h" */
/* #include "Config.h" */
/* #include "Status.h" */
/* #include "Analog.h" */
/* #include "AuxPort.h" */
/* #include "PhoneNumbers.h" */
/* #include "ex_eeprom.h" */
/* #include "Debug.h" */
/* #include "InputsHandlers.h" */

/* NOTE: Each Command must be start in this format ##xxxx. ,where  '##' is Command Token, xxxx - Password and point - end
 of Command. 
 Password maybe contains any characters, exclude ' ' '.' (space and point)  */

unsigned char Sys_Command_Buffer[SYS_COMMAND_BUFFER_SIZE];
//unsigned char Login_Of_UserName[20]; 
near bit SYS_COMMAND, LG_LOGIN_OF_USER;

unsigned char SMS_Commands[SMS_COMMANDS_QUEUE_MAX];
unsigned char pSMS_Commands = 0;
unsigned long RC_PressedKey;	  /* Remote Control */

unsigned char str[70];
unsigned char str_2[18];
unsigned char SMS_To_Delete = 0;

//bit DO_RESET;

near bit UserInList, CmdException;

//unsigned int Message_ID = 0;	  /* Random value - use as label for Set Date and Time */

unsigned char* Command_Line;

unsigned char CommandSource = 0;
unsigned char CommandHandler__Error;

/* for debug */
//unsigned char ds[6];
/*  */

unsigned char sBCD[8];

FUNCTION* Special;

#define   TEMP_STRING_SIZE		48
unsigned char g_t_str[TEMP_STRING_SIZE];

//void (*Execute_Module_1) (void) ;

//COMMAND_LINE bank1 CommandLine;

COMMAND_HEADER CommandHeader;

SMS_PACKET_RECEIVE SMS_Packet_Receive;

//#define   MESSAGE_FLAG	SMS_Pac


void Cmd_Return ( void )
{
	Execute_Module_1 = Command_Processor;
}

void SysReset ( void )
{
	PIN_MODEM_POWER = 0;
	delay_ms(1000);
	RESET();
}

int ExeSysCommand ( unsigned char *Command )
{
	if ( Execute_Module_1 == NULL )
	{

		if ( StrLen(Command) > 0 && StrLen(Command) < SYS_COMMAND_BUFFER_SIZE )
		{
			StrCpy(Sys_Command_Buffer, Command);
			SYS_COMMAND = TRUE;
			Execute_Module_1 = Command_Processor;
			return TRUE;
		}
		else
		{
			return -2;
		}
	} 


	return -1;
}


void SMS_Command_Delete ( void )
{
	static unsigned char State = 0, ErrCnt = 0;
	unsigned char Response;

	switch ( State )
	{
		case 0:
			if ( SMS_To_Delete == 0 )
			{
				Execute_Module_1 = NULL;
				return;
			}
			else
			{
				State++;
			}
			break;

		case 1:
			StrCpy( str, "AT+CMGD=" );
			LongToStr((str+errno), (unsigned long)SMS_To_Delete );
			StrCat( str, "\r");
			State++;
			ErrCnt = 8;
			break;

		case 2:
			
			Response = SendToModem( str, STR__OK, BUSY_SMS_COMMAND_DELETE );
			
			if ( Response != BUSY )
			{
				//lcd_clear_str(0,1);
				//putsf("  **********> BD \r", MODEM_PORT);
				if ( Response == TRUE )
				{
					dbg("\n SMS delete: OK\n"); //Dima
					Execute_Module_1 = Command_Processor;
					State = 0;
				}
				else
				{
					if ( ErrCnt == 0 )
					{
						//putsf("  **********> BD == END \r", MODEM_PORT);
						Execute_Module_1 = Command_Processor;
						State = 0;
					}
					else
					{
						//putsf("  **********> BD == FALSE \r", MODEM_PORT);
						ErrCnt--;
						//putsf("AT\r", MODEM_PORT );
						//delay_ms(200);
					}
				}
			}

			break;
			

		default :
			;
	}
} 

/* Handshake */
/* void CommandHandler_HD( void ) */
/* { */
/* 	unsigned char Password[5]; */

/* 	Execute_Module_1 = Command_Processor; */

/* 	Password_Generator( Password, ListCurrentCalls.PhoneNumber ); */

/* /\* 	lcd_clear_str(3,2); *\/ */
/* /\* 	lcd_puts(Password); *\/ */
/* /\* 	lcd_putchar(' '); *\/ */
/* /\* 	lcd_puts(Command_Line+2); *\/ */

/* 	if ( StrCmp(Password, Command_Line+2) == 0 )   */
/* 	{ */
/* 		StrCpy(ACK,"NX"); */
/* 	} */
/* 	else */
/* 	{ */
/* 		StrCpy(ACK,"ER02");		  /\* password is WRONG *\/ */
/* 	} */

/* 	DataMode_Transmitter(ACK, 0); */
/* } */
  

/* End of Session */
void CommandHandler_ES( void )
{
	Execute_Module_1 = Command_Processor;
  	//Send_ACK("NX");
	//DataModeTimeout = 2;
}

/* Software Update */
void CommandHandler_RS( void )
{
	SysReset();
}
 
/* Set Configuration Bits */
void 	CommandHandler_CB( void )
{
	Execute_Module_1 = Command_Processor;
	CharToHex((unsigned char*)&ConfigFile, (Command_Line + 2) );
	Config_Write();
	PrevState = 0;
}

void SMS_CreateHeader( unsigned char* Message, unsigned char* DestinationPhone )
{
	StrCpy( str, "AT+CMGS=\"");
	StrCat( Message, DestinationPhone);
	if ( DestinationPhone[0] == '+' )
		StrCat( Message, "\",145\r" ); 
	else
		StrCat( Message, "\",129\r"); 
	
	StrCat( Message, "##");		  /* Command Token */
	E2_Str_LoadFrom(PhoneNumber, E2_ADDR_MY_PHONE_NUMBER);
	Password_Generator( str_2, PhoneNumber );
	StrCat( Message, str_2);

	E2_Str_LoadFrom(str_2, E2_ADDR_MY_IMEI_NUMBER);
	StrCat( Message, str_2);
}
 
unsigned char SendStatus( unsigned char* DestinationPhone  )
{
	static unsigned char State = 0;//, str[70];
	unsigned char Response;
		  
	if ( State == 1 )
		goto SEND_STATUS;

	if ( State == 2 )
		goto WAIT_FOR_MODEM;

	Response = SendToModem( "AT+CCLK?\r", STR__OK, BUSY_SEND_STATUS );
	if ( Response != BUSY )
	{
		if ( Response == TRUE )
		{
			//StatusFile.DateTime = TimePackage( ModemRecBuffer );
			State++;
		}
		else
		{
			//delay_ms(100);
			return BUSY; 					  /* try again */
		}
	}
	else
	{
		return BUSY;
	}
	
  SEND_STATUS:
	
	StatusFile.ConfigFile = ConfigFile;
	StatusFile.StatusBits = StatusBits;
	//StatusFile.CDR_Index = CDR_AddressToIndex(CDR_Pointer);
	StatusFile.RSSI = RSSI;
	StatusFile.Battery = ATD_Result; 

	if ( CommandSource == AUX_PORT )
	{
		E2_Str_LoadFrom(str, E2_ADDR_MY_IMEI_NUMBER);
		puts(str, AUX_PORT);
		putsf("SS", AUX_PORT);
		HexToChar(str, (unsigned char*)&StatusFile, sizeof(STATUS_FILE) );
		puts(str, AUX_PORT);
		putsf( Revision_Basic+11, AUX_PORT);
		putch('\r', AUX_PORT);
		State = 0;
		//Execute_Module_1 = Command_Processor;
		return TRUE;
	}


	SMS_CreateHeader(str, DestinationPhone);
	StrCat(str, "SS");
	//HexToChar(str_2, (unsigned char*)&StatusFile, sizeof(STATUS_FILE) );
	HexToChar(&str[StrLen(str)], (unsigned char*)&StatusFile, sizeof(STATUS_FILE) );
	//StrCat(str, str_2);
	StrCat(str, (Revision_Basic+11));
	StrCat(str, "\x1A");
	
	State++;
	return BUSY;

  WAIT_FOR_MODEM:
	Response = SendToModem(str, STR__OK, BUSY_SEND_STATUS) ;
	if ( Response != BUSY )
	{
		State = 0;			  

		if ( Response == TRUE )
		{
			//Execute_Module_1 = Command_Processor;
			return TRUE;
		}
		else
		{
			return FALSE; /* try again */
		}
		
	}

	return BUSY;
	//##187B359811000013737SS7A884A0D2904000000000000A300504100001.40 $
   //      359811000013737SSD4884A0D2904000000000000A3004D4300001.40 $

}
 
void Send_Event( void )
{
	if ( SendStatus( NMS_PhoneNumber ) == TRUE )
	{
		Execute_Module_1 = NULL;
	}
}

/* Get Status File */
void CommandHandler_GS ( void )
{
	if ( SendStatus( SMS_Header.Field.PhoneNumber ) == TRUE )
	{
		Execute_Module_1 = Command_Processor;
	}
}
 


/* Remote Control. Set Key */
/* void CommandHandler_KE( void ) */
/* { */
/* //	unsigned char Buf[90]; */
/* //	ClearBuffer(Buf,90); */

/* 	Execute_Module_1 = Command_Processor; */

/* 	//lcd_print_str(Command_Line, 7,2,0); */

/* 	if ( Command_Line[2] == 'H' )	/\* HOOK_ON, HOOK_OFF *\/ */
/* 	{ */
/* 		PIN_HOOK ^= 1; */
/* 		PIN_HOOK_DIR = OUTPUT; */
/* 	} */
/* 	else */
/* 		if ( Command_Line[2] == 'X' )	/\* Release HOOK *\/ */
/* 		{ */
/* 			PIN_HOOK_DIR = INPUT; */
/* 		} */
/* 		else */
/* 			if ( Command_Line[2] == 'D' ) */
/* 			{ */
/* 				DISPLAY_ON ^= TRUE; */
/* 				Ext_Display_Update(); */
/* 			} */
/* 			else */
/* 			{ */
/* 				RC_PressedKey = Command_Line[2]; */
/* 			} */
/* } */
/* Remote Control. Display ON */
 
/* void CommandHandler_DO( void ) */
/* { */
/* 	DISPLAY_ON = TRUE; */
/* 	Execute_Module_1 = Command_Processor; */
/* } */

/* /\* Display OFF *\/  */
/* void CommandHandler_DF( void ) */
/* { */
/* 	DISPLAY_ON = FALSE; */
/* 	Execute_Module_1 = Command_Processor; */
/* } */
/* /\* END of Remote Control *\/ */

/* Add Customer Entry (Phone Number)  */
void CommandHandler_NA ( void )
{
	unsigned char Directory;
	unsigned char * pData;
	//unsigned char len;
	RECORD_CUSTOMER CustomerRecord;

	const char help[] = "\nAdd phone number; NAlp1 p2 pn\n l - list number; p1 - phone number 1, p2 - phone number 2, pn phone number n\n";

	int Address;						  /* For Debug ONLY! */

	Execute_Module_1 = Command_Processor;

	//putsf(">>NA\r", MODEM_PORT);
	//List = ListNumber_ToAddress(Command_Line[2] - '0' );
	Directory = Command_Line[2] - '0';
	
	if ( Directory >= DIRECTORIES_COUNT )
	{
		dbg(help); //Dima
		CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
		return;
	}
	
	
	pData = &Command_Line[3];

	for(;;)
	{
		/* get Phone number of User */

		if ( pData )
		{
			pData = StrCpy_UpTo_Ch(g_t_str, pData, ' ');
			Debug("\nphone: [%s]\n", g_t_str);
		}
		else
		{
			Debug("\nNA: end of phone list\n");
			CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
			return ;
		}
		
		
		if ( StrLen(g_t_str) > 0 )
		{
			StrToBCD(CustomerRecord.Phone, g_t_str, sizeof(CustomerRecord.Phone) );
			FlipFlopN(CustomerRecord.Phone, sizeof(CustomerRecord.Phone) );
		}
		else
		{
			Debug("\rNA: user phone ERROR (str_len = %d)", StrLen(g_t_str));
			CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
			return ;
		}
		
		/* Save data */
		Address = Ex_Entry_Write(Directory, (unsigned char*)&CustomerRecord);
		
		if ( Address == EX_ERROR )
		{
			Debug("\nNA: EEPROM ADDRESS: ERROR - 0x%X", Address );
			CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
			return ;
		}
		
		Debug("\n NA SUCCESS; EEPROM ADDRESS: 0x%X", Address );

	}
}

/* Delete List */
void CommandHandler_LD ( void )
{
	unsigned char List;
	const char help[] = 
		"\r Delete List: LDn n is:\r0-OWNERS\r1-USERS_GRP_1\r2-USERS_GRP_2\r3-USERS_GRP_3\n4-USERS_GRP_4\r5-Input Descriptors List\rA-delete all\r";
	Execute_Module_1 = Command_Processor;
	

	dbg("CommandHandler_LD\n"); //Dima

	if ( Command_Line[2] == 'A')
	{
		dbg("CommandHandler_LDA\n"); //Dima

		Ex_Entry_DeleteDirectory(DIRECTORY__OWNERS_LIST);
		Ex_Entry_DeleteDirectory(DIRECTORY__USER_LIST_1);
		Ex_Entry_DeleteDirectory(DIRECTORY__USER_LIST_2);
		Ex_Entry_DeleteDirectory(DIRECTORY__USER_LIST_3);
		Ex_Entry_DeleteDirectory(DIRECTORY__USER_LIST_4);
		Ex_Entry_DeleteDirectory(DIRECTORY__INPUTS_DESCRIPTORS_LIST);
		ih_registration();
		return;
	}

	List=Command_Line[2] - '0';

	if ( List >= DIRECTORIES_COUNT )
	{
		printf(help);
	}

	if ( Ex_Entry_DeleteDirectory(List) != TRUE )
	{
		printf(help);
	}
	

	ih_registration();

}

void CommandHandler_ND( void )
{
	unsigned int List;
	RECORD_CUSTOMER CustomerRecord;
	unsigned char *pData;
	const char help[] = 
		"\r\nDelete phone number; NDlp1 p2 pn\n\r l - list number; p1 - phone number 1, p2 - phone number 2, pn phone number n\r\n";

	int Address;						  /* For Debug ONLY! */

	Execute_Module_1 = Command_Processor;

	List = Command_Line[2] - '0';

	if ( List >= DIRECTORIES_COUNT )
	{
		putsf(help, AUX_PORT);
		CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
		return ;
	}


	pData = &Command_Line[3];

	for(;;)
	{
		/* get Phone number of User */

		if ( pData )
		{
			pData = StrCpy_UpTo_Ch(g_t_str, pData, ' ');
			Debug("\nphone: [%s]\n", g_t_str);
		}
		else
		{
			Debug("\nNA: end of phone list\n");
			CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
			return ;
		}
		
		
		if ( StrLen(g_t_str) > 0 )
		{
			StrToBCD(CustomerRecord.Phone, g_t_str, sizeof(CustomerRecord.Phone) );
			FlipFlopN(CustomerRecord.Phone, sizeof(CustomerRecord.Phone) );
		}
		else
		{
			Debug("\rNA: user phone ERROR (str_len = %d)", StrLen(g_t_str));
			CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
			return ;
		}
		
		/* Save data */
		Address = Ex_Entry_Delete(List, (unsigned char*)&CustomerRecord);
		
		if ( Address == EX_ERROR )
		{
			Debug("\nNA: EEPROM ADDRESS: ERROR - 0x%X", Address );
			CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
			return ;
		}
		
		Debug("\nND SUCCESS; EEPROM ADDRESS: 0x%X", Address );
	}
}

extern void RF_LearMode ( void );

unsigned long rf_inp;

/* Set(Add) Inputs descriptor */
void CommandHandler_IS ( void )
{
	unsigned int Address;
	unsigned char *pComLine, i, len;
	INPUTS_DESCRIPTOR InpDes;
	static unsigned char after_RF_LearMode = 0;

	
	if( Command_Line[2] == 'V' && after_RF_LearMode == 0 )
	{
		Execute_Module_1 = RF_LearMode;
		rf_inp = 0;
		after_RF_LearMode = 1;
		return;
	}
	else
	{
		Execute_Module_1 = Command_Processor;
	}

	if ( after_RF_LearMode )
	{
		if ( rf_inp )
		{
			InpDes.InputName = rf_inp; 
			pComLine = Command_Line+4;
		}
		else
		{
			dbg("\nIS FAIL. ERROR: RF INPUT\n"); //Dima
			CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
			goto EXIT;
		}
	}
	else
	{
		pComLine = Command_Line+2;

		/* Inputs Name */
		InpDes.InputName = StrToLong(pComLine);
		pComLine += errno;
	}

	/* Edge Alarm */
	InpDes.EventsOnEdge = StrToLong(pComLine);
	pComLine += errno+1;

	//Dima for ( i = 0; i < INPUTS_DESCRIPTOR_MESSAGE_SIZE; i++ )
	for ( i = 0; i < INPUTS_DESCRIPTOR_COMMANDS_COUNT; i++ )
	{
		if ( pComLine != NULL )
		{
			pComLine = StrCpy_UpTo_Ch(str, pComLine, ';'); /* message for groups */
		
			len = StrLen(str);
			if ( len > INPUTS_DESCRIPTOR_COMMAND_SIZE )
				str[INPUTS_DESCRIPTOR_COMMAND_SIZE+1] = 0;
			else
				str[len] = 0;
			StrCpy(InpDes.commands[i], str);
		}
		else
		{
			InpDes.commands[i][0] = '\0';
		}
	}

	//dbg("LIST_INPUTS_DESCRIPTORS: 0x%X", LIST_INPUTS_DESCRIPTORS); //Dima
	
	Address = Ex_Entry_Write(DIRECTORY__INPUTS_DESCRIPTORS_LIST, (unsigned char*)&InpDes);
	
	if ( Address != EX_ERROR )
	{
		//Debug("\nEEPROM ADDRESS: 0x%X\n", Address);
		dbg("\n\n ========== Input Set(IS)  SUCCESS ========\n\n"); //Dima
		CommandHandler__Error = 0;
	}
	else
	{
		dbg("\n!!!!!!! IS FAIL !!!!!!!");
		CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
	}

	ih_registration();

  EXIT:
	after_RF_LearMode = 0;
}

/* void Delete_Entry ( unsigned int List, unsigned char* EntryName ) */
/* { */
/* 	switch (  List ) */
/* 	{ */
/* 		case 0: */
			
/* 			break; */

/* 		case 1: */

/* 			break; */
			
/* 		case 3: */

/* 			break; */

/* 		default: */
/* 			; */
/* 	} */


/* } */
/* Input delete */
void CommandHandler_ID ( void )
{
	int EOL;							  /* End Of Line */
	//unsigned int List;
	unsigned char p = 2;//, pp;
	signed long InputName;
	int Address;						  /* For Debug ONLY! */

	Execute_Module_1 = Command_Processor;

	while(1)
	{
		EOL = StrReplaceChar(Command_Line+p, ' ', 0);
	
		InputName = StrToLong(Command_Line+p);
	
		if ( InputName > 0 )
		{
			Address = Ex_Entry_Delete(DIRECTORY__INPUTS_DESCRIPTORS_LIST, (unsigned char*)&InputName);
		
			if ( Address == EX_ERROR )
			{
				Debug("\nID: EEPROM ADDRESS (0x%X): NOT FOUND\n", Address );
				//return ;
			}
			else
				Debug(">>EEPROM ADDRESS: 0x%X\n", Address );
		}

		if ( EOL == (-1) )		/* if EOL == -1 then it's end of CommandLine ( next Phone not found) */ 
		{
			//CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
			ih_registration();
			return ;
		}

		p += ++EOL;
	}
}


/* void CommandHandler_SL ( void ) */
/* { */
/* 	unsigned int List; */

/* 	Execute_Module_1 = Command_Processor; */

/* 	List = ListNumber_ToAddress(Command_Line[2] -'0'); */
	
/* 	if ( List == UNKNOWN_GROUP ) */
/* 	{ */
/* 		putsf("\rShowList: SLn where n=0 for OWNER; n=1 for USERS\r", CommandSource); */
/* 		CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA; */
/* 	} */
/* 	else */
/* 	{ */
/* 		Ex_Show_List( List, CommandSource ); */
/* 	}  */

/* /\* 	if( Command_Line[2] == '0' ) *\/ */
/* /\* 	{ *\/ */
/* /\* 		Ex_Show_List( LIST_OWNERS, CommandSource ); *\/ */
/* /\* 	} *\/ */
/* /\* 	else *\/ */
/* /\* 		if ( Command_Line[2] == '1' ) *\/ */
/* /\* 		{ *\/ */
/* /\* 			Ex_Show_List( LIST_USERS_GROUP_1, CommandSource );  *\/ */
/* /\* 		} *\/ */
/* /\* 		else *\/ */
/* /\* 		{ *\/ */
/* /\* 			putsf("\rShowList: SLn where n=0 for OWNER; n=1 for USERS\r", CommandSource); *\/ */
/* /\* 		} *\/ */
/* } */
/* 
Example:
IF4 1 300 PANIC: Haim Ozer 12/2 Ramatgan$
Button - 4; Output 1 do pulse 30sec (300x100ms) send SMS message PANIC: ....
 */

void CommandHandler_TE ( void )
{
	unsigned char str[30], Result;
	Execute_Module_1 = Command_Processor;

	switch ( Command_Line[2] )
	{
		case 'D':
			if ( Command_Line[3] == '0' )
			{ 
				DebugOut_Enable = FALSE;
			}
			else
			{
				DebugOut_Enable = TRUE;
			}
			break;

		case 'X':
			Ex_ClearAll();
			putsf("\rDeleted\r>> Restart", AUX_PORT);
			SysReset();
			break;

		case 'I':
			E2_Delete(1, 1023);
			putsf("\rDeleted\r>> Restart", AUX_PORT);
			SysReset();
			break;

		case 'R':
			SysReset();
			break;

		case 'S':					  /* SIM operation */
			switch( Command_Line[3] )
			{
				case 'U':			  /* Unlock */
					StrCpy(str, "AT+CLCK=\"SC\",0,");
					break;

				case 'L':
					StrCpy(str, "AT+CLCK=\"SC\",1,");
					
					break;

				case 'C':			  /* Change password */
					StrCpy(str, "AT+CPWD=\"SC\",");
					break;

				default:
					putsf("\rSIM - Unlock: TESU\"password\"\rSIM - Lock: TESL\"password\"", AUX_PORT);
					putsf("\rSIM - Change Password: TESC\"old-password\",\"new-password\"\r", AUX_PORT);
					return;
			}
			
			StrCat(str, &Command_Line[4]); 
			StrCat(str,"\r"); 
			Result = SendToModem(str, STR__OK, BUSY_TE_SIM_OPERATION); 
			if ( Result != BUSY )
			{
				putch('\r', AUX_PORT);
				if ( Result == TRUE )
					putsf("OK\r", AUX_PORT);
				else
					putsf("ERROR\r", AUX_PORT);
			}
			else	
				Execute_Module_1 = CommandHandler_TE;
			return;
		default:
				putsf("> TEX - Delete all external EEPROM\r", AUX_PORT);
				putsf("> TEI - Delete all internal EEPROM\r", AUX_PORT);
				putsf("> TER - Restart\r", AUX_PORT);
				putsf("> TES - SIM operations\r", AUX_PORT);	
				putsf("> TED - Debug output ON/OFF (0/1)\r", AUX_PORT);	
		
			return;
	}

}
 
/* Output Set */
void CommandHandler_OS ( void )
{
	unsigned char out_num;
	unsigned int  out_val;

	Execute_Module_1 = Command_Processor;

	out_num = StrToLong(&Command_Line[2]);
	out_val = StrToLong(&Command_Line[4]);

	if ( out_num >= 1 && out_num <=5 && out_val >= 0 && out_val <=64000 )
	{
		out_set(out_num, out_val);
	}
	else
	{
		dbg("\nSet Output n for t time*100ms; OSn t\r  n = 1-5; t = 0-64000\nNote: if t = 1, forever\n"); //Dima
		CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
	}
}

void CommandHandler_RT ( void )
{
	/* static unsigned char Times, State = 0, i = 0; */
	/* int Errors; */
	/* RECORD_RF_REMOTE Received_RF_Remote; */

	/* switch ( State ) */
	/* { */
	/* 	case 0: */
			
	/*   FIND:		 */
	/* 		Errors = Ex_Entry_Read_ByIndex(LIST_RF_REMOTE, (unsigned char*)&Received_RF_Remote, i++);  */
	/* 		if ( Errors != EX_ERROR )	 */
	/* 		{ */
	/* 			if ( Errors != EX_ERROR__INDEX_IS_EMPTY && Received_RF_Remote.Special.Transmit == TRUE ) */
	/* 			{ */
	/* 				MemCpy(RF_Tx_Buffer, (unsigned char*)&Received_RF_Remote, 3); */
	/* 				Times = 20; */
	/* 				State++; */
	/* 			} */
	/* 			else */
	/* 				goto FIND; */
	/* 		} */
	/* 		else */
	/* 		{ */
	/* 			Debug("\rEnd of RF Remote Transmit"); */
	/* 			i = 0; */
	/* 			Execute_Module_1 = Command_Processor; */
	/* 			return;  */
	/* 		} */

	/* 	case 1: */
	/* 		RF_TX_START = TRUE; */
	/* 		PIN_RF_TX_ENABLE = TRUE; */
	/* 		State++; */
	/* 		break; */
			
	/* 	case 2: */
	/* 		if ( RF_TX_START == FALSE ) */
	/* 		{ */
	/* 			if ( --Times ) */
	/* 			{ */
	/* 				RF_TX_START = TRUE; */
	/* 				Debug("\rTr: %d", Times); */
	/* 			} */
	/* 			else */
	/* 			{ */
	/* 				State = 0; */
	/* 				PIN_RF_TX_ENABLE = FALSE; */
	/* 			} */
	/* 		} */
	/* 		break;	 */

	/* 	default:  */
	/* 		; */
	/* } */

	dbg("\nNOT SUPPORTED\n"); //Dima
}

void CommandHandler_LS ( void )
{
	signed char DirName = StrToLong(&Command_Line[2]);
 
	Execute_Module_1 = Command_Processor;

	
	if ( DirName < 0 || DirName >= DIRECTORIES_COUNT )
	{
		CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
		Debug("\nDirectory name is not exist\r");
		Debug("\n === Directory Name ===\nOWNERS_LIST - %d\nUSER_LIST_1 - %d\nUSER_LIST_2 - %d\nUSER_LIST_3 - %d\nUSER_LIST_4 - %d\nINP_DESCRIPT_LIST - %d\nCOMMAND_MACROS - %d\n ======================\r",

				DIRECTORY__OWNERS_LIST,
				DIRECTORY__USER_LIST_1,
				DIRECTORY__USER_LIST_2,
				DIRECTORY__USER_LIST_3,
				DIRECTORY__USER_LIST_4,
				DIRECTORY__INPUTS_DESCRIPTORS_LIST,
				DIRECTORY__COMMAND_MACROS);

		return;
	}  

	DirDescIndex = DirName;

//	Debug("\n Ex_Directory[%d].Print = 0x%X", DirName, (int)Ex_Directory[DirName].Print);
	
	
	/* Dima */
	if ( Ex_Directory[DirName].Print != NULL )
	{
		Execute_Module_1 = Ex_Directory[DirName].Print;
	}
	else
	{
		Debug("\nLS: Print of this directory not supported\r");
		CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
	}
}

/* define and set macro for command */
void CommandHandler_MS ( void )
{
	COMMAND_MACRO CmdMacro;
	unsigned char *p, s[20];
	int Result;

	Execute_Module_1 = Command_Processor;

	p = StrCpy_UpTo_Ch(s, &Command_Line[2], ' ');

	if ( p == NULL || StrLen(p) < 2 || StrLen(s) > CMD_MACRO_NAME_SIZE )
	{
	   Debug("\rMS: ERROR\r");
		CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
		return ;
	}
	else
	{
		StrCpy(CmdMacro.Name, s);
	}


	Debug("\rMacro Name: %s", CmdMacro.Name);
	Debug("\rMacro Command: %s", p);
	

	if ( cmd_add_cmd(p) == TRUE )
	{
		Execute_Module_1 = Command_Processor;

		StrCpy(CmdMacro.Macro, p);

		Result = Ex_Entry_Write(DIRECTORY__COMMAND_MACROS, (unsigned char*)&CmdMacro); 
		
		if ( Result != EX_ERROR )
		{
			Debug("\nMS: ADDRESS: 0x%X", Result);
		}
		else
		{
			Debug("\nMS: WRITE - ERROR");
		}
	}
	else
	{
		Debug("\rMS: No Correct Command: %s", p);
		CommandHandler__Error = COMMAND_HANDLER_ERROR__INPUT_DATA;
	}
}

/* Neighbor_Cells_Control */
void CommandHandler_NC ( void )
{
	if ( Command_Line[2] == 'L' )
	{
		Neighbor_Cells_Control ( Command_Line[2] );  
	}
	else 
		if ( Command_Line[2] == 'P' )
		{
			Neighbor_Cells_Print();
		}
		else
		{
			putsf("\n\nNeighbor_Cells_Control\n NCL - learn\n NCP - print saved cells\n\n", AUX_PORT);
		}

	Execute_Module_1 = Command_Processor;
}

unsigned char EP_Timeout;


#define   COMMAND_EXCEPTION_AMOUNT	5
#define   COMMAND_EXCEPTION_SIZE		12

unsigned char Command_Exception[COMMAND_EXCEPTION_AMOUNT][COMMAND_EXCEPTION_SIZE] = 
{
	"",
	"",
	"",
	"",
	""
}; 

void CommandHandler_AE ( void )
{
	unsigned char i;

	Execute_Module_1 = Command_Processor;
	
	for ( i = 0; i < COMMAND_EXCEPTION_AMOUNT; i++ )
	{
		if ( Command_Exception[i][0] == 0 ) 
		{
			if ( StrLen(&Command_Line[2]) < COMMAND_EXCEPTION_SIZE )
			{
				StrCpy(Command_Exception[i],&Command_Line[2]);
				break;
			}		 
		} 
	}

	for ( i = 0; i < COMMAND_EXCEPTION_AMOUNT; i++ )
	{
		Debug("Command_Exception[%d] = %s\n", i, Command_Exception[i]);
	}
}

unsigned char CheckForCmdException ( void )
{
#if defined(APP_CAR_PETROL_BLOCKING)
	CmdException = TRUE;
	return TRUE;
#else
	unsigned char i;

	Execute_Module_1 = Command_Processor;

	if ( StrLen(&Command_Line[2]) < TEMP_STRING_SIZE )
	{
		StrCpy(g_t_str, &Command_Line[2]);
		StrReplaceChar( g_t_str, '$', 0);
	}
	else
	{
		Debug("Cmd_AE: ERROR %d", -1);
		return 0;
	}

	dbg("\ncmd: [%s]\n", g_t_str); //Dima

	for ( i = 0; i < COMMAND_EXCEPTION_AMOUNT; i++ )
	{
		Debug("Command_Exception[%d]: [%s]\n", i, Command_Exception[i]);
		if ( !StrCmp(g_t_str,Command_Exception[i]) )
		{
			CmdException = TRUE;
			Debug("\n  Cmd_Excep: FOUND\n");
			return TRUE;
		}		 
	}

	return 0;
#endif

}
// "SML1 Alarm: IGNITION",
/* Send SMS message by phone number or by list of group number */
/* Command format: SMphone_OR_List SMS_Message; */
/* Example 1. < SML1 My SMS message > - send SMS to all Users from List (group) number 1  */
/* Example 2. < SM05201234567 My SMS message N21 > - send SMS to phone: 05201234567 */
void CommandHandler_SM ( void )
{
	static unsigned char State = 0;
	/* get pointer to SMS message */
	unsigned char* p;

	switch( State )
	{
		case 0:
			Execute_Module_1 = Command_Processor;

			p = FindCharNumber(&Command_Line[2], ' ', 1);
			if ( p == NULL )
			{
				CommandHandler__Error = 22;
				return ;
			}

			*(p-1) = 0;						  /* separe */

			CommandHandler__Error = SMS_Add_Message(&Command_Line[2], p);
			
			if ( CommandHandler__Error == 0 )
			{
				State++;
				Execute_Module_1 = CommandHandler_SM;
			}
			break;


		case 1:
			if ( Tools == NULL )
			{
				/* Get result of the task */
				if ( SMS_Sender_Result != SUCCESS ) 
				{
					CommandHandler__Error = SMS_Sender_Result; 
				}
				
				State = 0;
				Execute_Module_1 = Command_Processor;
			}
			break;

		default:
			;
	}
}

void CommandHandler_SP ( void )
{
	Execute_Module_1 = Command_Processor;
	puts(&Command_Line[2], AUX_PORT);
}

void Command_Init ( void )
{
	ClearBuffer( (unsigned char*)&SMS_Packet_Receive, sizeof(SMS_Packet_Receive) ); 
}

/* send by comport any input */
void CommandHandler_IE ( void )
{
	RC_PressedKey = StrToLong(&Command_Line[2]);
	Execute_Module_1 = Command_Processor;
}

void CommandHandler_MO( void )
{
	Execute_Module_1 = Command_Processor;
	if ( Command_Line[2] == 'A' )
	{
		SysState = STATE_ARM;
	}
	else
		if ( Command_Line[2] == 'D' )
		{
			SysState = IDLE;
		}
		else
		{
			if ( SysState == STATE_ARM )
				SysState = IDLE;
			else
				SysState = STATE_ARM;
		}

	dbg("\n\n === MODE: %s ===\n\n", SysState==STATE_ARM?"ARM":"DISARM"); //Dima
}

void CommandHandler_DI ( void )
{
	static unsigned char State = 0, tmr;
	unsigned char res;

	switch(State)
	{
		case 0:
			tmr = 10;
			sprintf(str,"ATD%s\r",&Command_Line[2]);
			State++;
			break;

		case 1:
			res = SendToModem( str, STR__OK, BUSY_DIALER );
			if ( res != BUSY )
			{
				State++;
			}
			break;

		case 2:
			if ( Time_1000ms && tmr-- == 0 )
			{
				State++;
			} 
			break;

		case 3:
			res = SendToModem( "ATH\r", STR__OK, BUSY_DIALER );
			if ( res != BUSY )
			{
				State = 0;
				Execute_Module_1 = Command_Processor;
			}
			break;
	}
}

const COMMAND_SET CommandsSet[] =
{
	{"IS", CommandHandler_IS},
	{"ID", CommandHandler_ID},
	{"IE", CommandHandler_IE},	  /* Input Event */
	{"NA", CommandHandler_NA},
	{"LS", CommandHandler_LS},
	{"ND", CommandHandler_ND},
	{"LD", CommandHandler_LD},
	{"RS", CommandHandler_RS},
	{"GS", CommandHandler_GS},
	{"TE", CommandHandler_TE},
	{"OS", CommandHandler_OS},
	{"MS", CommandHandler_MS},
	{"NC", CommandHandler_NC},
	{"AE", CommandHandler_AE},
	{"SM", CommandHandler_SM},
	{"SP", CommandHandler_SP},
	{"MO", CommandHandler_MO},
	{"DI", CommandHandler_DI},	  /* Dialer */
	{NULL,NULL}
};


void AddCommand( unsigned char SMS_Number )
{
	if ( SMS_Number )
	{
		SMS_Commands[pSMS_Commands] = SMS_Number;
		if ( ++pSMS_Commands == SMS_COMMANDS_QUEUE_MAX ) 
			pSMS_Commands = 0;
	}
}
 
unsigned char CommandHeader_Parsing( void )
{
	unsigned char FlagReg, BitNum;
	unsigned char Password[5];


	MemCpy( CommandHeader.Password, SMS_Buffer+OFFSET_PASSWORD, 4 );
	
	/* Password_Generator( Password, PhoneNumber );  */
	Password_Generator( Password, SMS_Header.Field.PhoneNumber ); 
	

	/* Check Password */
	if ( MemCmp(Password, CommandHeader.Password, 4) ) // && CheckForCmdException() != TRUE )  
	{
		Debug("\rPASSWORD - ERROR\n");	
		return FALSE;
	}

	// +CMGR: "REC READ","+972587482412",,"13/10/11,13:48:57+12"
	MemCpy( (unsigned char*)&CommandHeader.Message_ID, SMS_Buffer+OFFSET_MESSAGE_ID, TYPE_INTEGER );
	CharnToHex( (unsigned char*)&CommandHeader.Message_Number, SMS_Buffer+OFFSET_MESSAGE_NUMBER, TYPE_BYTE );	
	CharnToHex( (unsigned char*)&CommandHeader.Messages_Count, SMS_Buffer+OFFSET_MESSAGES_COUNT, TYPE_BYTE );	
	
	//putsf(" ******> CommandHeader.Messages_Count = ", MODEM_PORT);
	//putch(CommandHeader.Messages_Count+'0', MODEM_PORT);
	//putch('\r', MODEM_PORT);

	//putsf(" ******> SMS_Packet_Receive.Field.Message_ID = ", MODEM_PORT);
	//putds((unsigned char*)&SMS_Packet_Receive.Field.Message_ID, 2, MODEM_PORT);
	//putch('\r', MODEM_PORT);


	if ( SMS_Packet_Receive.Field.Message_ID == 0 ) /* not packets receive */
	{
		if ( SMS_Packet_Receive.Field.Last_Message_ID != CommandHeader.Message_ID )
		{
			if ( CommandHeader.Messages_Count > 1 )
			{
				SMS_Packet_Receive.Field.Last_Message_ID = CommandHeader.Message_ID;
			}
			SMS_Packet_Receive.Field.Message_ID = CommandHeader.Message_ID;
			SMS_Packet_Receive.Field.Messages_Count = CommandHeader.Messages_Count;
		}
		else
		{
			return FALSE;
		}
	}
	else
		if ( SMS_Packet_Receive.Field.Message_ID != CommandHeader.Message_ID )
		{
			if ( !StrCmp( "ST", SMS_Buffer+OFFSET_COMMAND_NAME) || errno == 2 ) //##XXXXVA0101ST$
				return OK;		  /* SET DATE and TIME */

			return FALSE;			  /* Delete the message, because it is not in this packet */
		} 

	BitNum = CommandHeader.Message_Number -1;	/* ( -1) - not exist packet with number 0 */
	FlagReg = 0;
	if ( BitNum > 31 ) /* unsigned long  */
	{
		BitNum -= 32;  
		FlagReg++;
	}
	
	if ( READ_BIT(SMS_Packet_Receive.Data[FlagReg], BitNum) == FALSE )
	{
		SET_BIT(SMS_Packet_Receive.Data[FlagReg], BitNum);
		SMS_Packet_Receive.Field.Messages_Count--;
	}


	//SMS_Packet_Receive.Field.Timeout = SMS_PACKET_RECEIVE_TIMEOUT;
	return OK;
}

COMMAND_MACRO CmdMacro; 
unsigned char cmd_add_cmd ( unsigned char* ComLine )
{
	unsigned char i;


	if ( StrLen(ComLine) == 0)
		return FALSE;

	dbg(""); //Dima

  FIND_COMMAND:

	for ( i = 0;  CommandsSet[i].CommandName != NULL;  i++ )
	{
		if ( !StrCmp(CommandsSet[i].CommandName, ComLine) || errno == 2  )
		{
			StrCpy(Command_Line, ComLine);
			Execute_Module_1 = CommandsSet[i].CommandHandler;
			return TRUE;
		}
	}

	StrCpy(CmdMacro.Name, ComLine);
	Debug("\rSearch macro: %s", CmdMacro.Name);
	
	
	if ( Ex_Entry_Read(DIRECTORY__COMMAND_MACROS, (unsigned char*)&CmdMacro) != EX_ERROR )
	{
		StrCpy(Command_Line, CmdMacro.Macro);
		Debug("Macro found\nCommmand Line: %s\n", Command_Line);
		goto FIND_COMMAND;
	}   
	
	Debug("\rMACRO OR COMMAND NOT FOUND\r");
	  						 
	return FALSE;
}

unsigned char Check_ListForUser ( void )
{
	Debug("\r Search User for number: %s", SMS_Header.Field.PhoneNumber+1);

	StrToBCD(sBCD, SMS_Header.Field.PhoneNumber+1, PHONE_NUMBERS_BCD_SIZE); //+1 - skip '+'
	FlipFlopN(sBCD, PHONE_NUMBERS_BCD_SIZE);

	if ( Ex_Entry_Find(DIRECTORY__USER_LIST_1, sBCD,0) != EX_ERROR )  
	{
		Debug("User found\n");
		UserInList = TRUE;
		return TRUE;				  /* if phone numbr found into User Group 1 */
	}

	UserInList = FALSE;
	Debug("\rUSER NOT FOUND!\r");

	return FALSE;
}

/* 
FFFFFFFFFFFFFFFF

>>
EEPROM ADDRESS: 1080

814797232597FFFF


 */
enum
{
	CHECK_FOR_COMMANDS = 0,
	LOAD_SMS_COMMANDS_BUFFER,
	LOAD_ONE_SMS_COMMAND,
	A_COM_PORT_LOAD_COMMAND,
	/* DATA MODE */
	DATA_MODE_LOAD_COMMAND,
	DATA_MODE_SEND_ACK,
	AUX_PORT_LOAD_COMMAND
};

void Command_Processor( void )
{
	static unsigned char State = CHECK_FOR_COMMANDS, NextCommand = 0;
	unsigned char Response;
	int Offset;
	
 	//lcd_print_str("ComProc", 2,2,0);
/* 	lcd_clear_str(0,3); */
/* 	lcd_print_Number(pSMS_Commands, LEFT); */
/* 	lcd_putsf(" "); */
/* 	lcd_print_Number(SMS_Commands[pSMS_Commands], LEFT); */
/* 	lcd_putsf(" "); */
/* 	lcd_print_Number(State, LEFT); */

	switch ( State )
	{
		case CHECK_FOR_COMMANDS:						  /* Check Command sources (1.SMS;  2.Aux. ComPort) */
			if ( SYS_COMMAND )
			{
				SYS_COMMAND = FALSE;
				Command_Line = Sys_Command_Buffer;
				CommandSource = SYS_APPLICATION;
				if ( cmd_add_cmd(Command_Line) == FALSE )
				{
					putsf("ER01\r\n",AUX_PORT);
					Execute_Module_1 = NULL;
					CommandSource = 0;
				}	
			}
			else
				if ( AUX_PORT_COMMAND )
				{
					CommandHandler__Error = 0;
					AUX_PORT_COMMAND = FALSE;
					CommandSource = AUX_PORT;
					Command_Line = AuxPortRecBuffer;
					if ( cmd_add_cmd(Command_Line) == FALSE )
					{
						putsf("ER99\r\n",AUX_PORT);
						Execute_Module_1 = NULL;
						CommandSource = 0;
					}	
				}
				else
					/* if ( DATA_MODE_COMMAND ) */
					/* { */
					/* 	DATA_MODE_COMMAND = FALSE; */
					/* 	State = DATA_MODE_LOAD_COMMAND; */
					/* 	CommandSource = MODEM_PORT; */
					/* 	Command_Line = ModemRecBuffer; */
					/* } */
					/* else  */
						if ( pSMS_Commands ) 
						{
							Debug("\rCommand Processor: SMS command\n", 0 );
							State = LOAD_SMS_COMMANDS_BUFFER;
							Command_Line = SMS_Buffer;
						}
						else
							if ( CommandSource == AUX_PORT )
							{
								CommandSource = 0;
								
								if ( CommandHandler__Error )
								{
									printf("\n ER%02d\r",CommandHandler__Error);
								}
								else
								{
									printf("\nNX\r\n");
								}
							}
							else
							{
								CommandSource = 0;
								Execute_Module_1 = NULL;
							}
			break;

		case DATA_MODE_SEND_ACK:
			State = CHECK_FOR_COMMANDS; 
			break;
			
		case DATA_MODE_LOAD_COMMAND:
			if ( cmd_add_cmd(Command_Line) == FALSE )	/* if command not found */
			{
				State = CHECK_FOR_COMMANDS; 
				//Send_ACK("ER01");				/* ERROR - UNKNOWN COMMAND */
			}
			else
			{
				State = CHECK_FOR_COMMANDS;
			}
			break;	

		case LOAD_SMS_COMMANDS_BUFFER:
			Response = SMS_Read(SMS_Buffer, SMS_Commands[pSMS_Commands-1], BUSY_COMMAND_PROCESSOR ); 
//			putsf(">><>\r", MODEM_PORT );
			if ( Response != BUSY )
			{
				//putsf(">>NOT_BUSY\r", MODEM_PORT );
				if ( Response == TRUE )
				{
					SMS_To_Delete = SMS_Commands[--pSMS_Commands]; /* delete SMS after executing */
			
					//putsf(">>TRUE\r", MODEM_PORT );
					//puts( (LongToStr(ds, SMS_To_Delete)), MODEM_PORT);
					//putsf("\r", MODEM_PORT );
					
					if ( (CommandHeader_Parsing() == OK) || (Check_ListForUser() == TRUE) || 
						  (CheckForCmdException() == TRUE) )
					{
						if ( UserInList || CmdException )
						{
							UserInList = FALSE;
							CmdException = FALSE;
							NextCommand = 2;
						}
						else
						{
							NextCommand = OFFSET_COMMAND_NAME; /* init. pointer to first command into SMS_Buffer */
						}
						State = LOAD_ONE_SMS_COMMAND;
					}
					else
					{
						Execute_Module_1 = SMS_Command_Delete;
						State = CHECK_FOR_COMMANDS;
					}

					SMS_Packet_Receive.Field.Timeout = SMS_PACKET_RECEIVE_TIMEOUT;

					//putsf(" ****************> COMMAND_PROCESSOR == FINISH\r", MODEM_PORT );
					//State = CHECK_FOR_COMMANDS;
					//CommandProcessor_Status = NOT_BUSY;
				}
				else
				{
					putsf(" >>> SMS_READ__FALSE\r ", MODEM_PORT );
					State = CHECK_FOR_COMMANDS;
					Execute_Module_1 = NULL;
				}
			}
			break;
//##3D585o0102AP01029C01!999999 010196!888888 0202BC02!001 01014A01!09 0101DC!08$NP05443322113 76543433211 0525628459$
// AT+CMGS="0523974963",129#013####3D585o0102AP01029C01!999999 0202BC02!001 0101DC!08$$NP05443322113 76543433211 0525628459$$$1A
//AT+CMGS="0523974963",129#013####3D585o0202NP0524879210 0524853291 0523974871$$$1A
//##3D585o0102AP01029C01!999999 0202BC02!001 0101DC!08$NP05443322113 76543433211 0525628459$

		case LOAD_ONE_SMS_COMMAND:
			Offset = StrReplaceChar( Command_Line+NextCommand, '$', 0); 
			if ( Offset != (-1) )
			{
				Command_Line += NextCommand;

				dbg("\ncmd_add_cmd(%s)\n",Command_Line); //Dima
				if ( cmd_add_cmd(Command_Line) == FALSE )	/* if command not found */
				{
					//putsf(" >>> UNKNOW COMND\r", MODEM_PORT);
					Execute_Module_1 = SMS_Command_Delete;
					State = CHECK_FOR_COMMANDS;
				}
				NextCommand = (unsigned char)Offset +1; 

				//lcd_clear_str(0, 2); 
				//lcd_putchar(Command_Line[0]);
				//lcd_putchar(Command_Line[1]);
				//lcd_putchar('-');
				//lcd_print_Number(NextCommand, LEFT);
				//delay_ms(1000);
								  
			}
			else
			{
				if ( SMS_Packet_Receive.Field.Messages_Count == 0 )
				{
					SMS_Packet_Receive.Data[0] = 0;
					SMS_Packet_Receive.Data[1] = 0;
					SMS_Packet_Receive.Data[2] = 0;
					
					putsf(" >>> SMS_PACKET_REC\r", MODEM_PORT);
				}

				Execute_Module_1 = SMS_Command_Delete;
				State = CHECK_FOR_COMMANDS;
//				CommandProcessor_Status = NOT_BUSY;
			}
			break;

		default:
			;
	}
}

